package com.backend.teamapi.service;

import com.backend.teamapi.dto.ApiDocumentRequestDTO;
import com.backend.teamapi.dto.ApiDocumentResponseDTO;
import com.backend.teamapi.model.ApiDocument;
import com.backend.teamapi.model.Team;
import com.backend.teamapi.model.User;
import com.backend.teamapi.repository.ApiDocumentRepository;
import com.backend.teamapi.repository.TeamRepository;
import com.backend.teamapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApiDocumentService {

    @Autowired
    private ApiDocumentRepository apiDocumentRepository;

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private UserRepository userRepository;

    public ApiDocumentResponseDTO createDocument(ApiDocumentRequestDTO dto, Long userId) {
        Team team = teamRepository.findById(dto.getTeamId())
                .orElseThrow(() -> new RuntimeException("Team not found"));
        User creator = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));

        ApiDocument doc = new ApiDocument();
        doc.setName(dto.getName());
        doc.setTeam(team);
        doc.setRequestType(dto.getRequestType());
        doc.setRequestUrl(dto.getRequestUrl());
        doc.setRequestHeader(dto.getRequestHeader());
        doc.setRequestBody(dto.getRequestBody());
        doc.setResponseBody(dto.getResponseBody());
        doc.setRemark(dto.getRemark());
        doc.setCreatedBy(creator);
        doc.setCreatedAt(LocalDateTime.now());

        ApiDocument saved = apiDocumentRepository.save(doc);
        return toResponseDTO(saved);
    }

    public List<ApiDocumentResponseDTO> getDocumentsByTeam(Long teamId) {
        Team team = teamRepository.findById(teamId)
                .orElseThrow(() -> new RuntimeException("Team not found"));
        List<ApiDocument> docs = apiDocumentRepository.findByTeam(team);
        return docs.stream().map(this::toResponseDTO).collect(Collectors.toList());
    }

    public ApiDocumentResponseDTO updateDocument(Long id, ApiDocumentRequestDTO dto, Long userId) {
        ApiDocument doc = apiDocumentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Document not found"));

        User updater = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));

        doc.setName(dto.getName());
        doc.setRequestType(dto.getRequestType());
        doc.setRequestUrl(dto.getRequestUrl());
        doc.setRequestHeader(dto.getRequestHeader());
        doc.setRequestBody(dto.getRequestBody());
        doc.setResponseBody(dto.getResponseBody());
        doc.setRemark(dto.getRemark());
        doc.setUpdatedBy(updater);
        doc.setUpdatedAt(LocalDateTime.now());

        ApiDocument updated = apiDocumentRepository.save(doc);
        return toResponseDTO(updated);
    }

    //删除接口文档
    public void deleteDocument(Long id, Long userId) {
        ApiDocument doc = apiDocumentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Document not found"));
    
        // 校验用户是否有权限（示例仅判断是否为创建者，可扩展为团队成员权限）
        if (!doc.getCreatedBy().getId().equals(userId)) {
            throw new RuntimeException("You do not have permission to delete this document");
        }
    
        apiDocumentRepository.delete(doc);
    }
    

    private ApiDocumentResponseDTO toResponseDTO(ApiDocument doc) {
        ApiDocumentResponseDTO dto = new ApiDocumentResponseDTO();
        dto.setId(doc.getId());
        dto.setName(doc.getName());
        dto.setTeamId(doc.getTeam().getId());
        dto.setTeamName(doc.getTeam().getName());
        dto.setRequestType(doc.getRequestType());
        dto.setRequestUrl(doc.getRequestUrl());
        dto.setRequestHeader(doc.getRequestHeader());
        dto.setRequestBody(doc.getRequestBody());
        dto.setResponseBody(doc.getResponseBody());
        dto.setRemark(doc.getRemark());
        dto.setCreatedBy(doc.getCreatedBy().getId());
        dto.setCreatedByName(doc.getCreatedBy().getUsername());
        dto.setCreatedAt(doc.getCreatedAt());
        if (doc.getUpdatedBy() != null) {
            dto.setUpdatedBy(doc.getUpdatedBy().getId());
            dto.setUpdatedByName(doc.getUpdatedBy().getUsername());
            dto.setUpdatedAt(doc.getUpdatedAt());
        }
        return dto;
    }
}